﻿/*----------------------------------------------------------------
  //Copyright (C) 2012 赵国伟
  //文件名：GoodsManage.cs
  //文件功能描述：商品管理
  //创建人：赵国伟
  //生成时间：2012/03/17 16:15:00
//----------------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Shopping.Common;
using Shopping.Model;
using Shopping.DAL;
using System.Collections;

namespace Shopping.BLL
{
    public class GoodsManage
    {
        private readonly DALGoods dalGoods = new DALGoods();
        private readonly DALGoodsPriceRules dalPriceRules = new DALGoodsPriceRules();
        private readonly DALGoodsOnSales dalOnSales = new DALGoodsOnSales();
        private readonly DALGoodsPictures dalPicture = new DALGoodsPictures();
        private readonly DALGoodsEvaluates dalEvaluate = new DALGoodsEvaluates();
        private readonly DALGoodsPriceConds dalPriceCond = new DALGoodsPriceConds();
        private const string _goodsViewHistory = "goodsViewHistory";
        private const int _goodsCookieExpire = 7 * 24;

        #region "更新商品的点击数；by 赵国伟 2012-03-18"
        /// <summary>
        /// 更新商品的点击数；
        /// </summary>
        /// <param name="GoodsID"></param>
        /// <returns></returns>
        public int UpdateClicks(int GoodsID)
        {
            return dalGoods.UpdateClicks(GoodsID);
        }
        #endregion

        #region "将基本的Goods Model对象，转化为 GoodsInfo核心业务对象； by 赵国伟 2012-04-08"
        /// <summary>
        /// 将基本的Goods Model对象，转化为 GoodsInfo核心业务对象；
        /// </summary>
        /// <param name="listOfSource"></param>
        /// <returns></returns>
        private List<GoodsInfo> LoadProperty(List<GoodsInfo> listOfSource)
        {

            if (listOfSource != null)
            {
                List<string> listOfGoodsID = new List<string>();
                foreach (GoodsInfo s in listOfSource)
                {
                    listOfGoodsID.Add(s.BaseInfo.GoodsID.ToString());
                }
                Dictionary<int, GoodsPictures> dictMainPicture = QueryMainPicturesToHash(listOfGoodsID);
                foreach (GoodsInfo s in listOfSource)
                {
                    if (dictMainPicture.ContainsKey(s.BaseInfo.GoodsID))
                        s.MainPicture = dictMainPicture[s.BaseInfo.GoodsID];
                }
            }

            return listOfSource;
        }
        #endregion

        #region "分页查询商品数据 by 赵国伟 2012-04-08"
        /// <summary>
        /// 分页查询商品数据
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public List<GoodsInfo> QueryListAsPage(QueryGoodsAsPage p)
        {
            StringBuilder sbCond = new StringBuilder("1=1 ");
            if (!string.IsNullOrEmpty(p.KeyWords))
            {
                sbCond.AppendLine(" and (BrandName + GoodsName+PlaceName+CategoryName) like '%" + p.KeyWords + "%' ");
            }

            if (p.TCategoryID > 0)
                sbCond.AppendLine(" and CategoryID=" + p.TCategoryID);
            else
            {
                if (p.SCategoryID > 0)
                    sbCond.AppendLine(" and CategoryID in(Select CategoryID from Categories where CategoryID=" + p.SCategoryID + " or ParentID=" + p.SCategoryID + ") ");
                else
                {
                    if (p.FCategoryID > 0)
                    {
                        sbCond.AppendLine(" and (CategoryID=" + p.FCategoryID);
                        sbCond.AppendLine(" or CategoryID in(Select CategoryID from Categories Where ParentID in(Select CategoryID From Categories Where ParentID=" + p.FCategoryID + ")) ");
                        sbCond.AppendLine(" or CategoryID in(Select CategoryID From Categories Where ParentID=" + p.FCategoryID + ") ");
                        sbCond.AppendLine(")");
                    }
                }
            }

            if (p.BrandID > 0)
                sbCond.AppendLine(" and BrandID=" + p.BrandID);
            if (p.GoodsPlaceID > 0)
                sbCond.AppendLine(" and GoodsPlaceID=" + p.GoodsPlaceID);
            if (p.SpecialAreaID > 0)
                sbCond.AppendLine(" and SpecialAreaID = " + p.SpecialAreaID);

            if (p.PackUnitID > 0)
            {
                sbCond.AppendLine(" and GoodsID in (Select GoodsID from  GoodsOnSales Where PackUnitID=" + p.PackUnitID + ")");
            }
            if (p.GoodsPriceCondID > 0)
            {
                GoodsPriceConds price = dalPriceCond.GetModel(p.GoodsPriceCondID);
                sbCond.AppendLine(" and SalePrice >=" + price.MinPrice);
                sbCond.AppendLine(" and SalePrice <=" + price.MaxPrice);
            }
            if (p.CommendCategoryID > 0)
            {
                sbCond.AppendLine(" and GoodsID in(Select GoodsID From GoodsCommend Where CategoryID=" + p.CommendCategoryID + ") ");
            }

            if (!string.IsNullOrEmpty(p.SaleStatus))
                sbCond.AppendLine(" and SaleStatus='" + p.SaleStatus + "'");

            if (!string.IsNullOrEmpty(p.Status))
                sbCond.AppendLine(" and Status='" + p.Status + "'");
            else
                sbCond.AppendLine(" and Status<>'" + Status.已删除.ToString() + "' ");

            string orderby = GetOrderBy(p.Sorts);
            List<GoodsInfo> listOfSource = dalGoods.QueryListAsPageEx(sbCond.ToString(), orderby, p.CurPage, p.PageSize, out p.TotalCount);
            return LoadProperty(listOfSource);
        }
        #endregion


        #region "查询指定商品的详细信息； by 赵国伟 2012-04-08"
        /// <summary>
        /// 查询指定商品的详细信息；
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public GoodsInfo GetGoods(int goodsId)
        {
            GoodsInfo source = dalGoods.GetModelEx(goodsId);
            if (source != null)
            {
                List<GoodsOnSales> listOfOnSales = dalOnSales.QueryList("GoodsID=" + goodsId, "IsMajor desc,GoodsOnSaleID"); //by 赵国伟2012-08-07 增加；
                source.OnSales = new List<GoodsOnSalesInfo>();
                Dictionary<int, string> dictPack = DictionariesManage.GetDictionariesToHash(DictionaryCategory.包装类型);
                foreach (GoodsOnSales o in listOfOnSales)
                {
                    GoodsOnSalesInfo oi = new GoodsOnSalesInfo();
                    oi.OnSale = o;
                    oi.PackUnitName = dictPack[o.PackUnitID];
                    source.OnSales.Add(oi);
                }

                source.PriceRules = dalPriceRules.QueryList("GoodsID=" + goodsId, "MinQuantity,CreateDate asc");
                source.Pictures = QueryPictures(goodsId);
                source.GoodsCommends = DALHelper.QueryIDNameObjs<Dictionaries>("DictionaryID in(Select CategoryID From GoodsCommend Where GoodsID=" + goodsId + ")", DictionariesEnum.DictionaryName);
                source.Packs = DALHelper.QueryIDNameObjs<Goods>("GoodsID in(Select RelateGoodsID from GoodsPacks Where GoodsID=" + goodsId + ")", GoodsEnum.GoodsName);
                var picList = source.Pictures != null ? source.Pictures.Where(pic => pic.IsMajor) : new List<GoodsPictures>();
                source.MainPicture = picList != null && picList.Count() == 0 ? null : picList.ToArray()[0];
            }
            return source;
        }
        #endregion

        #region "返回指定排序方式的排序语句 by 赵国伟 2012-04-08"
        /// <summary>
        /// 返回指定排序方式的排序语句
        /// </summary>
        /// <param name="sorts"></param>
        /// <returns></returns>
        private string GetOrderBy(int sorts)
        {
            string orderby = "OrderValue,CreateDate desc,GoodsID desc";
            switch (sorts)
            {
                case 1:
                    orderby = "CreateDate desc,GoodsID desc"; //创建日期降序排列；
                    break;
                case 2:
                    orderby = "CreateDate asc,GoodsID desc"; //创建日期升序排列
                    break;
                case 3:
                    orderby = "Clicks desc,GoodsID desc";    //点击量降序排列；
                    break;
                case 4:
                    orderby = "Clicks asc,GoodsID desc";     //点击量升序排列；
                    break;
                case 5:
                    orderby = "SalePrice desc,GoodsID desc"; //按销售价格降序排列；
                    break;
                case 6:
                    orderby = "SalePrice asc,GoodsID desc";  //按销售价格升序排列；
                    break;
                case 7:
                    orderby = "Quantity desc,GoodsID desc"; //按销量降序排列；
                    break;
                case 8:
                    orderby = "Quantity asc, GoodsID desc";//按销量升序排列；
                    break;
                case 9:
                    orderby = "CommentCounts  desc,GoodsID desc"; //按评价数降序排列；
                    break;
                case 10:
                    orderby = "CommentCounts  asc,GoodsID desc"; // 按评价数升序排列；
                    break;
                case 11:
                    orderby = "Stocks desc,GoodsID desc"; //按库存数降序排列；
                    break;
                case 12:
                    orderby = "Stocks asc,GoodsID desc"; //按库存数升序排列；
                    break;
                case 13:
                    orderby = "OnSaleDate desc,GoodsID desc"; //按上架日期降序排列；
                    break;
                case 14:
                    orderby = "OnSaleDate asc,GoodsID desc"; //按上架日期升序排列；
                    break;

            }
            return orderby;
        }
        #endregion

        #region "保存商品信息； by 赵国伟 2012-04-08"
        /// <summary>
        /// 保存商品信息；
        /// </summary>
        /// <param name="g"></param>
        /// <returns></returns>
        public ReturnValue SaveGoods(GoodsInfo g)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail, "保存失败！");
            g.BaseInfo.GoodsName = g.BaseInfo.GoodsName.Replace("'", "''");

            //进行数据必要的检查；
            if (dalGoods.QueryList(1, "GoodsName like '%" + g.BaseInfo.GoodsName + "%' and GoodsID<>" + g.BaseInfo.GoodsID + " and Status<>'" + Status.已删除.ToString() + "'", "") != null)
            {
                ret.Message = "商品名称重复！";
                return ret;
            }
            FilesManage.FormatGoodsImgs(g); //处理商品图片；

            #region "设置商品的上下架日期"

            g.BaseInfo.OffSaleDate = null;
            g.BaseInfo.OnSaleDate = null;
            if (g.BaseInfo.SaleStatus == GoodsSaleStatus.已上架.ToString())
                g.BaseInfo.OnSaleDate = DateTime.Now;
            else if (g.BaseInfo.SaleStatus == GoodsSaleStatus.已下架.ToString())
                g.BaseInfo.OffSaleDate = DateTime.Now;

            #endregion

            g.BaseInfo.LastModifyDate = DateTime.Now;
            g.BaseInfo.CreateDate = DateTime.Now;

            if (g.BaseInfo.GoodsID > 0)
            {
                Goods o = dalGoods.GetModel(g.BaseInfo.GoodsID);
                g.BaseInfo.CreateDate = o.CreateDate;
                g.BaseInfo.Clicks = o.Clicks;
                if (g.BaseInfo.SalePrice < o.SalePrice) //如果价格下降了则记录最新的下调日期；
                    g.BaseInfo.LastDownPriceDate = DateTime.Now;
                else if (g.BaseInfo.SalePrice > o.SalePrice) //如果涨价了，则清除掉价格下调日期；
                    g.BaseInfo.LastDownPriceDate = null;

                if (g.BaseInfo.SaleStatus == o.SaleStatus)
                {
                    g.BaseInfo.OnSaleDate = o.OnSaleDate;
                    g.BaseInfo.OffSaleDate = o.OffSaleDate;
                }

            }
            if (g.PriceRules != null)
            {
                foreach (GoodsPriceRules rule in g.PriceRules)
                    rule.CreateDate = DateTime.Now;
            }
            if (g.Pictures != null)
            {
                foreach (GoodsPictures pic in g.Pictures)
                    pic.CreateDate = DateTime.Now;
            }
            return dalGoods.Save(g);
        }
        #endregion

        #region "查询指定商品的图片信息； by 赵国伟 2012-04-10"
        /// <summary>
        /// 查询指定商品的图片信息；
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public List<GoodsPictures> QueryPictures(int goodsId)
        {
            return dalPicture.QueryList("GoodsID=" + goodsId, "GoodsPictureID asc");
        }
        #endregion

        #region "批量查询商品的主图；并存为Hash结构 ； by 赵国伟 2012-05-07"
        /// <summary>
        /// 批量查询商品的主图；并存为Hash结构 ；
        /// </summary>
        /// <param name="goodsIDs"></param>
        /// <returns></returns>
        public Dictionary<int, GoodsPictures> QueryMainPicturesToHash(List<string> goodsIDs)
        {
            Dictionary<int, GoodsPictures> dict = new Dictionary<int, GoodsPictures>();
            List<GoodsPictures> list = dalPicture.QueryList("IsMajor=1 and GoodsID in('" + string.Join("','", goodsIDs.ToArray()) + "')", "");
            if (list != null)
            {
                foreach (GoodsPictures p in list)
                {
                    if (!dict.ContainsKey(p.GoodsID))
                        dict.Add(p.GoodsID, p);
                }
            }

            return dict;
        }
        #endregion

        #region 查询销售排行

        public List<GoodsInfo> GetSaleTopGoods(int top)
        {
            string strWhere = "Status='" + Status.正用.ToString() + "' and SaleStatus='" + GoodsSaleStatus.已上架.ToString() + "' ";
            string orderby = GetOrderBy(7);
            var goodsreader = dalGoods.QueryListEx(top, strWhere, orderby);
            return LoadProperty(goodsreader);
        }

        #endregion

        #region 商品浏览记录，把商品放入Cookie by 党明 2012-04-26
        /// <summary>
        /// 商品浏览记录
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public void SetGoodsToHistory(int goodid)
        {
            string goodslist = Utility.GetCookies(_goodsViewHistory);
            if (!string.IsNullOrEmpty(goodslist))
            {
                List<string> good = goodslist.Split(',').ToList<string>();
                good.Remove(goodid.ToString());
                good.Insert(0, goodid.ToString());
                goodslist = string.Join(",", good.ToArray());
            }
            else
            {
                goodslist += goodid;
            }
            Utility.SetCookies(_goodsViewHistory, goodslist, "", _goodsCookieExpire);
        }
        #endregion

        #region 取商品浏览记录，把商品放入Cookie by 党明 2012-04-26
        /// <summary>
        /// 商品浏览记录
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public List<Goods> GetGoodsToHistory()
        {
            string goodslist = Utility.GetCookies(_goodsViewHistory);
            Dictionary<int, Goods> good = dalGoods.QueryList(10, " where GoodsID in (" + goodslist + ")", "").ToDictionary(p => p.GoodsID);
            List<string> ids = goodslist.Split(',').ToList<string>();
            List<Goods> list = new List<Goods>();
            foreach (string id in ids)
            {
                if (good.ContainsKey(Convert.ToInt32(id)))
                    list.Add(good[Convert.ToInt32(id)]);
            }
            return list;
        }
        #endregion

        #region "获取商品查询的条件数据 by 赵国伟 2012-05-06"
        /// <summary>
        /// 获取商品查询的条件数据
        /// </summary>
        /// <returns></returns>
        public GoodsFilter GetGoodsFilter(QueryGoodsAsPage q)
        {
            string cond = string.Format("Where Status='{0}' and SaleStatus='{1}'", Status.正用.ToString(), GoodsSaleStatus.已上架.ToString());
            if (q.SCategoryID > 0)
                cond += " and (CategoryID=" + q.SCategoryID + " or CategoryID in (Select CategoryID from Categories Where ParentID=" + q.SCategoryID + "))";
            else
            {
                if (q.FCategoryID > 0)
                {
                    cond += " and CategoryID in (Select CategoryID from Categories Where     ";
                    cond += " CategoryID= "+ q.FCategoryID;
                    cond += " or ParentID =" + q.FCategoryID;
                    cond += " or ParentID in (Select CategoryID from Categories Where ParentID=" + q.FCategoryID + ")";
                    cond += ")";
                }
            }

            GoodsFilter c = new GoodsFilter();
            if (q.SCategoryID > 0)
                c.listOfCategory = DALHelper.QueryIDNameObjs("Select  CategoryID,CategoryName from Categories Where Status='" + Status.正用.ToString() + "' and ParentID=" + q.SCategoryID);
            else if (q.FCategoryID > 0)
                c.listOfCategory = DALHelper.QueryIDNameObjs("Select  CategoryID,CategoryName from Categories Where Status='" + Status.正用.ToString() + "' and ParentID=" + q.FCategoryID);

            c.listOfPrice = DALHelper.QueryIDNameObjs("Select GoodsPriceCondID,PriceCondName From GoodsPriceConds Order by MinPrice");
            c.listOfPlace = DALHelper.QueryIDNameObjs("Select GoodsPlaceID,PlaceName From GoodsPlaces Where Status='" + Status.正用.ToString() + "' and GoodsPlaceID in(Select GoodsPlaceID From Goods " + cond + " ) Order by OrderValue,CreateDate desc");
            c.listOfUnit = DALHelper.QueryIDNameObjs("Select DictionaryID,DictionaryName From Dictionaries Where Status='" + Status.正用.ToString() + "' and Category='" + DictionaryCategory.包装类型.ToString() + "' and DictionaryID in(Select PackUnitID From GoodsOnSales Where GoodsID in (Select GoodsID from Goods " + cond + ") )  Order by OrderValue,CreateDate desc");


            BrandsManage bllBrand = new BrandsManage();
            c.listOfBrand = bllBrand.QueryBrands(q.FCategoryID, q.SCategoryID, 0, true);

            return c;
        }
        #endregion

        #region "删除一条指定的商品信息； by 赵国伟 2012-05-29"
        /// <summary>
        /// 删除一条指定的商品信息；
        /// </summary>
        /// <param name="goodsId"></param>
        /// <returns></returns>
        public ReturnValue DeleteGoods(int goodsId)
        {
            ReturnValue ret = new ReturnValue(ResultType.Fail, "删除失败！");
            try
            {
                if (dalGoods.Delete(goodsId) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "删除成功！";
                }
            }
            catch
            {
                if (DALHelper.SetTableStatus<Goods>(goodsId, Status.已删除.ToString()) > 0)
                {
                    ret.Result = ResultType.Success;
                    ret.Message = "删除成功！";
                }
            }
            return ret;
        }
        #endregion


        #region "获取指定用户收藏的商品 by 赵国伟 2012-08-18"
        /// <summary>
        /// 获取指定用户收藏的商品；
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public List<GoodsInfo> GetFavoriteGoods(int userId)
        {
            string strWhere = "Status='" + Status.正用.ToString() + "' and SaleStatus='" + GoodsSaleStatus.已上架.ToString() + "' ";
            strWhere += " and GoodsID in(Select GoodsID from UserFavorites Where UserID=" + userId + ")";
            string orderby = GetOrderBy(7);
            var goodsreader = dalGoods.QueryListEx(0, strWhere, orderby);
            return LoadProperty(goodsreader);

        }
        #endregion

        #region "将商品列表数据转为Hash结构 by 赵国伟 2012-08-18"
        /// <summary>
        /// 将商品列表数据转为Hash结构
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public Dictionary<int, GoodsInfo> ListToHash(List<GoodsInfo> list)
        {
            Dictionary<int, GoodsInfo> dict = new Dictionary<int, GoodsInfo>();
            if (list != null)
            {
                foreach (GoodsInfo l in list)
                {
                    dict.Add(l.BaseInfo.GoodsID, l);
                }
            }
            return dict;
        }
        #endregion




    }
}
